package com.linux.huhx.concurreny;

import java.awt.image.DataBuffer;
import java.util.concurrent.Exchanger;

public class FillAndEmpty {
    Exchanger<String> exchanger = new Exchanger<String>();
    String initialEmptyBuffer = null;
    String initialFullBuffer = "full";

    class FillingLoop implements Runnable {
        public void run() {
            String currentBuffer = initialEmptyBuffer;
            try {
                while (currentBuffer != null) {
                    currentBuffer = exchanger.exchange(currentBuffer);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    class EmptyingLoop implements Runnable {
        public void run() {
            String currentBuffer = initialFullBuffer;
            try {
                while (currentBuffer != null) {
                    if (currentBuffer.isEmpty())
                        currentBuffer = exchanger.exchange(currentBuffer);
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    void start() {
        new Thread(new FillingLoop()).start();
        new Thread(new EmptyingLoop()).start();
    }
}

